#!/usr/bin/env bash
#
# Summary: Migrate cpan modules from other version
#
# Usage: plenv migrate-modules <from> <to>
#
#  -n: Do not run test cases while installing by cpanm
#
# See `plenv versions` for a complete list of installed versions.
#

set -e

# Provide plenv completions
if [ "$1" = "--complete" ]; then
  exec plenv versions --bare
fi

if [ -z "$PLENV_ROOT" ]; then
  PLENV_ROOT="${HOME}/.plenv"
fi

no_test=""
for args in "$@"
do
  if [ "$args" = "-n" ]; then
    no_test="-n"
    shift
  fi
done

FROM="$1"
case "$FROM" in
"" | -* )
  # We can remove the sed fallback once plenv 0.4.0 is widely available.
  { plenv-help migrate-modules 2>/dev/null ||
    sed -ne '/^#/!q;s/.\{1,2\}//;1,4d;p' < "$0"
  } >&2
  exit 1
  ;;
esac

TO="$2"
case "$TO" in
"" | -* )
  # We can remove the sed fallback once plenv 0.4.0 is widely available.
  { plenv-help migrate-modules 2>/dev/null ||
    sed -ne '/^#/!q;s/.\{1,2\}//;1,4d;p' < "$0"
  } >&2
  exit 1
  ;;
esac

echo "Migrating $FROM to $TO"

PLENV_VERSION=$TO plenv install-cpanm
PLENV_VERSION=$FROM perl -MExtUtils::Installed -e 'for (ExtUtils::Installed->new(skip_cwd => 1)->modules) {next if /\APerl\z/; print $_, "\n";}' | PLENV_VERSION=$TO cpanm $no_test --mirror-only
PLENV_VERSION=$TO plenv rehash
